<script setup lang="ts">
import { useIntersectionObserver } from '@vueuse/core';
import { ref, useTemplateRef, watch } from 'vue';

import type { InfiniteEmits, InfiniteProps } from './types';

const props = withDefaults(defineProps<InfiniteProps>(), {
  isFinished: false
});
const loadingRef = useTemplateRef<HTMLDivElement>('loadingRef');

const isLoading = defineModel({ default: true });

const emits = defineEmits<InfiniteEmits>();

const loadingRefIsIntersecting = ref(false);
useIntersectionObserver(loadingRef, ([{ isIntersecting }]) => {
  loadingRefIsIntersecting.value = isIntersecting;
  loadMore();
});

function loadMore() {
  if (loadingRefIsIntersecting.value && !isLoading.value && !props.isFinished) {
    isLoading.value = true;
    emits('loadMore');
  }
}

watch(isLoading, () => setTimeout(loadMore, 100));

defineOptions({ name: 'MInfinite' });
</script>

<template>
  <div>
    <slot />
    <div ref="loadingRef" class="h-6 py-4">
      <MSvgIcon
        class="mx-auto h-4 w-4 animate-spin"
        name="infinite-load"
        v-show="isLoading"
      />
      <p v-if="props.isFinished" class="text-center text-base text-zinc-400">
        已经没有更多数据了
      </p>
    </div>
  </div>
</template>
